package com.example.mediastore;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.room.Room;
import androidx.viewpager.widget.ViewPager;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.Log;
import android.webkit.MimeTypeMap;
import android.widget.TextView;
import android.widget.Toast;

import com.example.mediastore.adapter.PagerAdapter;
import com.example.mediastore.bean.FileBean;
import com.example.mediastore.constant.Constant;
import com.example.mediastore.database.FileDataBase;
import com.example.mediastore.fragment.ExampleFragment;
import com.example.mediastore.thread.MyThreadPool;
import com.example.mediastore.utils.CommonUtil;
import com.google.android.material.tabs.TabLayout;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.TimeZone;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CountDownLatch;

public class MainActivity extends AppCompatActivity {

    private final String[] typeList = {"ALL","PDF", "PPTX","DOCX", "XLSX", "ETT", "MP3", "MP4", "JPG"};
    private final Integer[] iconList = {R.mipmap.pdf, R.mipmap.ppt, R.mipmap.doc, R.mipmap.excel, R.mipmap.ett, R.mipmap.mp3, R.mipmap.mp4, R.mipmap.image};

    //定义图标集合
    // 存储文件信息的哈希表
    private final ConcurrentHashMap<String, List<FileBean>> hashMap = new ConcurrentHashMap<>();
    private TabLayout tabLayout;
    private ViewPager viewPager;

    static MyThreadPool threadPool = new MyThreadPool();


    private List<String> pathList=new ArrayList<>();

    private FileDataBase fileDataBase;
    private List<FileBean> mergeList = new ArrayList<>(); // 将 mergeList 提升为类的成员变量
    private List<FileBean> fileBeanList;
    private CountDownLatch countDownLatch;
    private PagerAdapter adapter;


    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fileDataBase = Room.databaseBuilder(this, FileDataBase.class, "file").build();

        initView();
        checkDatabaseData();
        requestStoragePermission();

    }

    private void checkDatabaseData() {
        threadPool.getExecutorService().submit(() -> {
            fileBeanList = fileDataBase.fileDao().findAll();
            if (mergeList.size() > 0) {
                initViewAndEvent();
            }
        });
    }

    private void initData(PagerAdapter adapter, String s) {
        ExampleFragment fragment = new ExampleFragment();
        Bundle bundle = new Bundle();
        if (s.equals("ALL")){
            bundle.putSerializable("fileList", (Serializable) mergeList);
        }else{
           bundle.putSerializable("fileList", (Serializable) hashMap.get(s.toLowerCase()));
           Log.d(Constant.TAG, "fileList: "+ hashMap.get(s.toLowerCase()));

        }

        fragment.setArguments(bundle);
        adapter.addFragment(fragment, s);
    }

    private void scanMediaAndDisk(){
        countDownLatch = new CountDownLatch(2);

        threadPool.getExecutorService().submit(new ScanMedia());
        threadPool.getExecutorService().submit(new ScanDisk());


        try {
            countDownLatch.await(); // 等待媒体库扫描和磁盘扫描完成
            threadPool.getExecutorService().submit(new Runnable() {
                @Override
                public void run() {
                    fileDataBase.fileDao().insertBatch(mergeList);
                }
            });
            initViewAndEvent();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }



    private PagerAdapter createPagerAdapter() {
        PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager());

        for (String s : typeList) {
            initData(adapter, s);
        }

        return adapter;
    }

    private void requestStoragePermission() {
        //安卓版本大于6小于11采用弹窗申请方式,存储权限变成了特殊权限
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
            int permissionCheck = ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE);
            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
               // scanMediaAndDisk();
            } else {
                ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
            }
        }
        //获取安卓的版本,如果大于等于11,采用意图申请方式，存储权限变成了危险权限
        else {
            if (Environment.isExternalStorageManager()) {
                scanMediaAndDisk();
            } else {
                Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                Uri uri = Uri.fromParts("package", getPackageName(), null);
                intent.setData(uri);
                startActivityForResult(intent, 1);
            }
        }
    }



    @SuppressLint({"Range", "SetTextI18n"})
    public class ScanMedia implements Runnable {
        @Override
        public void run() {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                try {
                    fileBeanList = CommonUtil.scanMediaStore(MainActivity.this, hashMap);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            mergeList.addAll(fileBeanList);
            for (FileBean fileBean : fileBeanList) {
                pathList.add(fileBean.getPath());
            }
            countDownLatch.countDown();
        }
    }

    // 初始化视图
    private void initView() {
        //获取对应的控件
        tabLayout = findViewById(R.id.tab_layout);
        viewPager = findViewById(R.id.view_pager);

    }

    //扫描磁盘
    private class ScanDisk implements Runnable {
        @Override
        public void run() {
            // 扫描磁盘
            CommonUtil.FileSearcher fileSearcher = new CommonUtil.FileSearcher(hashMap,typeList,iconList);
            try {
                List<FileBean> fileBeanList = CommonUtil.FileSearcher.searchFiles(new File(Environment.getExternalStorageDirectory().getPath()));

                Log.d(Constant.TAG, "磁盘扫描完成: "+fileBeanList.size());
                for (FileBean fileBean : fileBeanList) {
                    if (!pathList.contains(fileBean.getPath())){
                        mergeList.add(fileBean);
                        List<FileBean> list = hashMap.computeIfAbsent(fileBean.getFileType(), k -> new ArrayList<>());
                        list.add(fileBean);
                    }
                }
                Log.d(Constant.TAG, "mergeList: "+mergeList.size());
                countDownLatch.countDown();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }




    private void initViewAndEvent() {
        adapter = createPagerAdapter();
        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                if (Environment.isExternalStorageManager()) {
                    scanMediaAndDisk();
                } else {
                    Toast.makeText(this, "请先授权", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
}
